package com.yzyz.web.controller.visitor;

import java.io.OutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.AbstractController;

import com.yzyz.utils.RandomChars;
import com.yzyz.utils.ValidateKey;

/**
 * 产生随即码
 * @author david.sun
 * @date 2010-7-14
 */
public class GetValidateKey extends AbstractController {

	@Override
	protected ModelAndView handleRequestInternal(HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		ValidateKey vi = new ValidateKey();
		vi.setHeight(40);
		vi.setWidth(120);
		
		char c1 = RandomChars.chars[Integer.valueOf(String.valueOf(Math.round(Math.random() * 61)))];
		char c2 = RandomChars.chars[Integer.valueOf(String.valueOf(Math.round(Math.random() * 61)))];
		char c3 = RandomChars.chars[Integer.valueOf(String.valueOf(Math.round(Math.random() * 61)))];
		char c4 = RandomChars.chars[Integer.valueOf(String.valueOf(Math.round(Math.random() * 61)))];
		char [] chars = new char[]{c1, c2, c3, c4};
		String key = String.valueOf(c1) + String.valueOf(c2) + String.valueOf(c3) + String.valueOf(c4);
		request.getSession(true).setAttribute("validateKey", key);
		OutputStream out = response.getOutputStream();
		out = vi.getDefaultImage(chars, out);
		response.setContentType("image/jpeg");
		response.setHeader("Content-Disposition", "attachment; filename=validateKey.jpg");
		response.flushBuffer();
		out.close();
		return null;
	}

}
